<template>
  <div class="simple-personnel-list">
    <div v-if="personnelCount === 0" class="empty-list">
      <el-empty description="暂无人员" :image-size="60" />
    </div>
    
    <div v-else class="personnel-content">
      <div class="personnel-header">
        <span class="summary-text">共 {{ personnelCount }} 人</span>
      </div>
      
      <div class="personnel-items">
        <UserInfo
          v-for="(person, index) in displayPersonnel" 
          :key="`${person.id}-${index}`"
          :userId="person.id"
          :user-info="person"
          :show-avatar="true"
          :show-name="true"
          :show-account="true"
          :avatar-size="24"
          class="personnel-item"
        />
        <span v-if="personnelCount > 3" class="more-text">等 {{ personnelCount }} 人</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, watch, ref } from 'vue'
import UserInfo from '@/components/UserInfo/index.vue'
import { getPersonnelList } from '@/api/workflow/process.api'

const props = defineProps({
  assignees: { type: Array, default: () => [] }
})

const emit = defineEmits(['view-detail', 'personnel-updated'])

const loading = ref(false)
const convertedPersonnel = ref([])
const lastProcessedAssignees = ref(null) // 记录上次处理的assignees，避免重复处理

// 防抖函数
const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 转换assignees数据格式
const convertAssignees = async (assignees) => {
  // 检查是否正在加载中
  if (loading.value) {
    return
  }
  
  // 检查是否与上次处理的数据相同
  const currentAssigneesStr = JSON.stringify(assignees)
  if (lastProcessedAssignees.value === currentAssigneesStr) {
    return
  }
  
  if (!assignees || !Array.isArray(assignees) || assignees.length === 0) {
    convertedPersonnel.value = []
    lastProcessedAssignees.value = currentAssigneesStr
    emit('personnel-updated', [])
    return
  }
  
  // 设置加载状态
  loading.value = true
  
  try {
    // 检查第一个assignee的数据格式
    const firstAssignee = assignees[0]
    
    // 如果第一个assignee有id和nickName字段，说明是直接用户数据格式
    if (firstAssignee.id && firstAssignee.nickName) {
      // 检测到直接用户数据格式，直接使用
      // 避免重复设置相同数据
      if (JSON.stringify(convertedPersonnel.value) !== JSON.stringify(assignees)) {
        convertedPersonnel.value = assignees
        emit('personnel-updated', assignees)
      }
      lastProcessedAssignees.value = currentAssigneesStr
      return
    }
    
    // 检测到assignees格式，需要转换
    const allIds = []
    const roleIds = []
    const deptIds = []
    const postIds = []
    const userIds = []
    
    // 收集所有ID
    assignees.forEach(assignee => {
      if (assignee.value && Array.isArray(assignee.value)) {
        assignee.value.forEach(item => {
          if (item.id) {
            allIds.push(item.id)
            
            // 根据类型分类
            if (assignee.type === 'role') {
              roleIds.push(item.id)
            } else if (assignee.type === 'dept') {
              deptIds.push(item.id)
            } else if (assignee.type === 'post') {
              postIds.push(item.id)
            } else if (assignee.type === 'user') {
              userIds.push(item.id)
            }
          }
        })
      }
    })
    
    // 如果没有收集到任何ID，尝试从assignee.value中直接提取用户信息
    if (allIds.length === 0) {
      assignees.forEach(assignee => {
        if (assignee.value && Array.isArray(assignee.value)) {
          assignee.value.forEach(item => {
            if (item.id || item.userId) {
              allIds.push(item.id || item.userId)
              userIds.push(item.id || item.userId)
            }
          })
        }
      })
    }
    
    // 构建查询参数
    const queryParams = {}
    
    if (roleIds.length > 0) {
      queryParams.roleIds = roleIds
    }
    
    if (deptIds.length > 0) {
      queryParams.deptIds = deptIds
    }
    
    if (postIds.length > 0) {
      queryParams.postIds = postIds
    }
    
    if (userIds.length > 0) {
      queryParams.userIds = userIds
    }
    
    // 调用API查询人员信息
    const result = await queryPersonnelInfo(queryParams)
    
    // 避免重复设置相同数据
    if (JSON.stringify(convertedPersonnel.value) !== JSON.stringify(result)) {
      convertedPersonnel.value = result
      emit('personnel-updated', result)
    }
    
    // 记录已处理的数据
    lastProcessedAssignees.value = currentAssigneesStr
    
  } finally {
    // 清除加载状态
    loading.value = false
  }
}

// 查询人员信息
const queryPersonnelInfo = async (queryParams) => {
  try {
    const responseData = await getPersonnelList(queryParams)
    
    if (responseData && Array.isArray(responseData) && responseData.length > 0) {
      // 处理API返回的数据，数量: responseData.length
      
      // 转换为统一的人员数据格式
      const allPersonnel = responseData.map(person => ({
        id: person.id,
        nickName: person.nickName || person.userName,
        userName: person.userName,
        avatar: person.avatar,
        type: person.type || 'user',
        source: 'API查询'
      }))
      
      return allPersonnel
    } else {
      // API返回的数据为空或格式不正确: responseData
      return []
    }
  } catch (error) {
    // 没有收集到任何ID，尝试从assignee.value中直接提取用户信息
    console.warn('查询人员信息失败，使用fallback数据:', error)
    
    // 使用fallback数据
    const fallbackPersonnel = []
    props.assignees.forEach(assignee => {
      if (assignee.value && Array.isArray(assignee.value)) {
        assignee.value.forEach(item => {
          if (item.id || item.userId) {
            fallbackPersonnel.push({
              id: item.id || item.userId,
              nickName: item.nickName || item.name || item.userName || '未知用户',
              userName: item.userName || item.account || item.id || item.userId,
              avatar: item.avatar || '',
              type: 'user',
              source: 'fallback数据'
            })
          }
        })
      }
    })
    
    return fallbackPersonnel
  }
}

// 防抖版本的转换函数
const debouncedConvertAssignees = debounce(async (assignees) => {
  await convertAssignees(assignees)
}, 300)

// 监听assignees变化，自动转换人员
watch(() => props.assignees, async (newAssignees, oldAssignees) => {
  // 避免无限循环：检查数据是否真的发生了变化
  if (JSON.stringify(newAssignees) === JSON.stringify(oldAssignees)) {
    return
  }
  
  if (newAssignees && newAssignees.length > 0) {
    await debouncedConvertAssignees(newAssignees)
  } else {
    convertedPersonnel.value = []
    lastProcessedAssignees.value = null
    emit('personnel-updated', [])
  }
}, { immediate: true }) // 移除 deep: true，避免深度监听导致的循环

// 计算人员数量
const personnelCount = computed(() => {
  const count = convertedPersonnel.value.length
  return count
})

// 显示的人员预览（最多显示3个）
const displayPersonnel = computed(() => {
  const display = convertedPersonnel.value.slice(0, 3)
  return display
})

// 暴露方法给父组件
defineExpose({
  // 获取转换后的人员列表
  getPersonnel: () => convertedPersonnel.value,
  
  // 手动转换assignees
  convertAssignees: (assignees) => convertAssignees(assignees),
  
  // 获取人员数量
  getPersonnelCount: () => personnelCount.value,
  
  // 获取显示的人员预览
  getDisplayPersonnel: () => displayPersonnel.value,
  
  // 设置转换后的人员列表
  setPersonnel: (personnel) => {
    convertedPersonnel.value = personnel
    emit('personnel-updated', personnel)
  }
})
</script>

<style scoped>
.simple-personnel-list {
  margin-bottom: 8px;
}

.empty-list {
  padding: 6px 0;
  text-align: center;
  min-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-list :deep(.el-empty) {
  padding: 0;
}

.empty-list :deep(.el-empty__image) {
  width: 32px;
  height: 32px;
}

.empty-list :deep(.el-empty__description) {
  margin-top: 2px;
  font-size: 12px;
  color: #909399;
}

.personnel-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.personnel-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-text {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.personnel-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.personnel-item {
  margin: 0;
}

.more-text {
  font-size: 12px;
  color: #909399;
}
</style> 